using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using TEngine;
using System;
using DG.Tweening;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using Sirenix.Utilities;
using System.Linq;

namespace GameLogic
{
    [Window(UILayer.UI, fullScreen: true)]
    /// <summary>
    /// 算数大师戏主界面
    /// </summary>
    class Pan_GameMath : UIWindow
    {

        private class LevelInfo
        {
            public int Row;
            public int Col;

            public int level;

        }

        #region UI Components
        [SerializeField] private Button m_btnClose; // 关闭按钮
        [SerializeField] private Button m_btnHit; // 提示按钮
        [SerializeField] private RectTransform m_rectMatrix; // 矩阵容器
        [SerializeField] private RectTransform m_rectTarget;
        private MatrixCtrl m_matrixCtrl; // 矩阵控制器
        private WindowAnimationHelper m_animationHelper; // 窗口动画辅助
        private EventTriggerListener m_eventTriggerListener;
        #endregion

        #region Game Logic Fields

        private LevelInfo m_levelInfo;
        private System.Random m_random = new System.Random(); // 随机数生成器
        private Dictionary<Vector2Int, CellCtrl_MathMaster> m_dictSelectedCells = new();// 已选中的单元格

        private List<int> m_targetNums = new();// 目标数字

        //数字数量
        private int m_numCount = 2;
        private int m_targetNumCount = 3;
        //运算符
        private List<string> m_operators = new() { "+" };
        #endregion

        #region Lifecycle Methods
        protected override void BindMemberProperty()
        {
            m_btnClose = FindChildComponent<Button>("m_btnClose");
            m_btnHit = FindChildComponent<Button>("m_btnHit");
            m_rectMatrix = FindChildComponent<RectTransform>("GameView/m_rectMatrix");
            m_rectTarget = FindChildComponent<RectTransform>("m_target");
            m_matrixCtrl = m_rectMatrix.gameObject.GetOrAddComponent<MatrixCtrl>();
            m_animationHelper = new WindowAnimationHelper(this);
            m_eventTriggerListener = EventTriggerListener.Get(gameObject);
        }

        protected override void RegisterEvent()
        {
            m_btnClose.onClick.AddListener(OnClose);
            m_btnHit.onClick.AddListener(OnOnHintClick);
            m_eventTriggerListener.OnClick += OnMatrixClick;
        }


        protected override void OnCreate()
        {
            m_animationHelper.Initialize();
            InitializeGameBoard();
        }

        protected override async void OnRefresh()
        {
            await m_animationHelper.PlayOpenAnimation();
        }

        protected override void OnDestroy()
        {
            m_animationHelper.Cleanup();
            m_btnClose.onClick.RemoveAllListeners();
            m_btnHit.onClick.RemoveAllListeners();
            base.OnDestroy();
        }
        #endregion

        #region Core Game Logic
        /// <summary>
        /// 初始化游戏棋盘
        /// 1. 生成可解的数字布局
        /// 2. 初始化矩阵控制器
        /// 3. 创建所有单元格并初始化数值
        /// </summary>
        private void InitializeGameBoard()
        {
            m_matrixCtrl.Initialize<CellCtrl_MathMaster>(5, 5, m_rectMatrix, "CellCtrl_MathMaster​");
            m_matrixCtrl.GetAllCells<CellCtrl_MathMaster>().ForEach(cell => cell.InitializeValue(m_random.Next(1, 10)));

            // 生成目标数字
            var cellValues = m_matrixCtrl.GetAllCells<CellCtrl_MathMaster>();
            List<int> values = new();
            foreach (var cell in cellValues)
            {
                if (cell.GetCurrentState() == CellCtrl_MathMaster.CellState.Normal)
                    values.Add(cell.Value);
            }

            for (int i = 0; i < m_targetNumCount; i++)
            {
                m_targetNums.Add(GenerateTargetNumber(values, 2, m_operators));
                var targetCell = GameModule.Resource.LoadGameObject("TargetCell_Math",m_rectTarget).GetComponent<TargetCell_Math>();
                targetCell.SetValue(m_targetNums[i]);
                targetCell.SetCellState(TargetCell_Math.CellState.Normal);
            }

        }

        #region 数字生成与计算逻辑
        /// <summary>
        /// 生成目标数字（基于单元格数值和运算符组合）
        /// </summary>
        /// <param name="cellValues">所有可用单元格数值列表</param>
        /// <param name="numCount">随机选取的数字数量（默认2个）</param>
        /// <param name="operators">允许的运算符列表（默认加减乘）</param>
        private int GenerateTargetNumber(List<int> cellValues, int numCount = 2, List<string> operators = null)
        {
            if (cellValues == null || cellValues.Count == 0)
                throw new ArgumentException("单元格数值列表不能为空");

            if (numCount < 2 || numCount > 4)
                throw new ArgumentException("数字数量需在2-4之间");

            operators = operators ?? new List<string> { "+", "-", "*" };

            // 随机选取数字
            var selectedNumbers = new List<int>();
            for (int i = 0; i < numCount; i++)
            {
                selectedNumbers.Add(cellValues[m_random.Next(cellValues.Count)]);
            }

            // 生成运算符
            var selectedOperators = new List<string>();
            for (int i = 0; i < numCount - 1; i++)
            {
                selectedOperators.Add(operators[m_random.Next(operators.Count)]);
            }

            return CalculateExpressionResult(selectedNumbers, selectedOperators);
        }

        /// <summary>
        /// 计算表达式结果（支持运算优先级）
        /// </summary>
        private int CalculateExpressionResult(List<int> numbers, List<string> operators)
        {
            var nums = new List<int>(numbers);
            var ops = new List<string>(operators);

            // 先处理乘除
            for (int i = 0; i < ops.Count;)
            {
                if (ops[i] == "*" || ops[i] == "/")
                {
                    int a = nums[i];
                    int b = nums[i + 1];
                    int tempResult = ops[i] == "*" ? a * b : HandleDivision(a, b);

                    nums[i] = tempResult;
                    nums.RemoveAt(i + 1);
                    ops.RemoveAt(i);
                }
                else
                {
                    i++;
                }
            }

            // 处理加减
            int result = nums[0];
            for (int i = 0; i < ops.Count; i++)
            {
                if (ops[i] == "+")
                {
                    result += nums[i + 1];
                }
                else // "-"
                {
                    result -= nums[i + 1];
                    if (result < 0) result += nums[i + 1] * 2;
                }
            }
            return result > 0 ? result : 1;
        }

        /// <summary>
        /// 处理整除运算
        /// </summary>
        private int HandleDivision(int dividend, int divisor)
        {
            if (divisor == 0) divisor = 1;
            while (dividend % divisor != 0)
            {
                divisor--;
            }
            return dividend / divisor;
        }
        #endregion

        /// <summary>
        /// 生成目标数字
        /// </summary>


        #endregion

        #region Helper Methods

        #endregion

        #region Events
        private async void OnClose()
        {
            await m_animationHelper.PlayCloseAnimation();
            Close();
        }
        private void OnOnHintClick()
        {

        }

        private void OnMatrixClick(GameObject go, PointerEventData ev)
        {
            if (!m_matrixCtrl.ScreenToGrid(ev.position, out var currentPos)) return;
            if (m_dictSelectedCells.TryGetValue(currentPos, out var cell))
            {
                m_dictSelectedCells.Remove(currentPos);
                cell.SetCellState(CellCtrl_MathMaster.CellState.Normal);
            }
            else
            {
                var cellNew = m_matrixCtrl.GetCell<CellCtrl_MathMaster>(currentPos);
                if (cellNew != null)
                {
                    m_dictSelectedCells[currentPos] = cellNew;
                    cellNew.SetCellState(CellCtrl_MathMaster.CellState.Selected);
                }
            }

            if (m_dictSelectedCells.Count >= m_numCount)
            {
                var value = CalculateExpressionResult(m_dictSelectedCells.Values.Select(cell => cell.Value).ToList(), m_operators);
                bool isOk = false;
                for(int i = 0; i < m_targetNums.Count;i++) 
                {
                    int num = m_targetNums[i];
                }

                if  (!isOk)
                {
                }
            }
        }

        #endregion
    }
}
